package com.hui.server.util;

import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;
import java.util.UUID;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.util
 * @Author: HUI
 * @CreateTime: 2022-04-17 11:23
 * @Description: 文件上传与下载工具类
 */

@Slf4j
public class FileUtil {
    private static final String SYSTEM_NAME = System.getProperty("user.dir") + "\\yeb-server\\src\\main\\resources\\files";


    /**
     * 文件传至本地，文件名以 "-"分割来查找
     *
     * @param file
     * @param port
     * @return
     */
    public static String uploadFile(MultipartFile file, String port) {
        if (!ObjectUtils.isEmpty(file) || !StringUtils.isNullOrEmpty(port)) {
            String filename = file.getOriginalFilename();

            //获得当前项目的路径，与 resources目录进行拼接
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String localFileName = SYSTEM_NAME + "/" + uuid + "-" + filename;//filename放在最后面，因为有后缀名
            String hostAddress = "";
            try {
                file.transferTo(new File(localFileName));
                hostAddress = InetAddress.getLocalHost().getHostAddress();

                return "http://" + hostAddress + ":" + port + "/admin/downloadface/" + filename;

            } catch (IOException e) {
                log.error("文件上传异常：{}", e.getMessage());
                return hostAddress;
            }

        }
        return "";
    }

    /**
     * 根据文件名，返回完整路径名
     *
     * @param filename
     * @return
     */
    public static String downloadFile(String filename) {
        File[] files = new File(SYSTEM_NAME).listFiles();
        String[] name = null;//要下载文件的名字
        String replace = "";
        if (Optional.ofNullable(files).isPresent()) {
            for (File file : files) {
                replace = file.toString().replace(SYSTEM_NAME, "");
                name = replace.split("-");
                boolean equals = name[1].equalsIgnoreCase(filename);
                if (equals) {
                    log.info("完整文件路径名：{}",file.toString());
                    return file.toString();
                }
            }
        }
        //返回 null表示没找到
        return "";
    }


}
